package com.motion.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.motion.generator.entity.UserFocus;
import com.motion.generator.mapper.UserFocusMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service
public class UserFocusService {
     @Autowired(required = false)
    UserFocusMapper userFocusMapper;

    public int getRelation(Long user1, Long user2){
        QueryWrapper<UserFocus> queryWrapper1 = new QueryWrapper<UserFocus>();
        QueryWrapper<UserFocus> queryWrapper2 = new QueryWrapper<UserFocus>();
        queryWrapper1.eq("userId", user1);
        queryWrapper1.eq("focusedUserId", user2);

        if (userFocusMapper.selectObjs(queryWrapper1).isEmpty()){
            queryWrapper2.eq("focusedUserId", user1);
            queryWrapper2.eq("userId", user2);
            if(userFocusMapper.selectObjs(queryWrapper2).isEmpty()){
                return 0; //user1和user2没有关系
            }
            return 2;  //user2是user1的粉丝
        }else{
            queryWrapper2.eq("focusedUserId", user1);
            queryWrapper2.eq("userId", user2);
            if(userFocusMapper.selectObjs(queryWrapper2).isEmpty()){
                return 1; //user1是user2的粉丝
            }
            return 3;  //user2和user1互相关注
        }
    }

    public List<Long> getFocusIdList(Long userId){
        QueryWrapper<UserFocus> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("focusedUserId").orderByDesc("createTime").eq("userId", userId);
        List<Long> lst = new LinkedList<>();
        for(Object id: userFocusMapper.selectObjs(queryWrapper)){
            lst.add(Long.valueOf(String.valueOf(id)));
        }
        return lst;
    }

    public IPage<UserFocus> getFocus(Long userId, Long currentPage, Long pageSize){
        QueryWrapper<UserFocus> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("createTime").eq("userId", userId);

        return userFocusMapper.selectPage(new Page<>(currentPage, pageSize), queryWrapper);
    }

    public IPage<UserFocus> getFans(Long userId, Long currentPage, Long pageSize){
        QueryWrapper<UserFocus> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("createTime").eq("focusedUserId", userId);

        return userFocusMapper.selectPage(new Page<>(currentPage, pageSize), queryWrapper);
    }

    public void createFocus(UserFocus userFocus){
        userFocusMapper.insert(userFocus);
    }

    public void cancelFocus(Long usr1, Long usr2){
        //usr1表本用户， usr2表要取关的用户
        QueryWrapper<UserFocus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", usr1).eq("focusedUserId", usr2);
        userFocusMapper.delete(queryWrapper);
    }

}

